import { ref, reactive } from 'vue'

export default (options = {}) => {
	const search = reactive(options.search || {})
	const list = ref([])
	const total = ref(0)
	const page = ref(1)
	const limit = ref(10)
	const loading = ref(false)

	// 查询
	const handleQuery = async () => {
		loading.value = true
		try {
			const res = await options.queryApi({
				limit: limit.value,
				page: page.value,
				...search
			})
			loading.value = false
			if (!res.code) {
				list.value = [...list.value, ...res.data.list]
				total.value = res.data.total
			}
		} catch (err) {
			loading.value = false
		}
	}
	// 加载更多
	const loadMore = () => {
		if (total.value > list.value.length) {
			page.value++
			handleQuery()
		}
	}
	// 点击搜索
	const handleSearch = () => {
		page.value = 1
		list.value = []
		handleQuery()
	}
	// 清空搜索
	const handleClearSearch = () => {
		Object.keys(search).forEach(key => {
			switch (search[key]) {
				case 'string':
					search[key] = ''
					break
				case 'number':
					search[key] = 0
					break
				case 'boolean':
					search[key] = false
					break
				case 'object':
					search[key] = Array.isArray(search[key]) ? [] : {}
					break
				default:
					search[key] = null
			}
		})

		handleSearch()
	}

	return {
		search,
		list,
		total,
		page,
		limit,
		loading,

		loadMore,
		handleQuery,
		handleClearSearch,
		handleSearch
	}
}
